package gdepot



import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = false)
class GoodsController {

    static allowedMethods = [save: "POST", delete: "DELETE"]


    def index(Integer max) {
        /*params.max = Math.min(max ?: 10, 100)*/
        if (!params.max)  params.max=9
        respond Goods.list(params), model:[goodsInstanceCount: Goods.count()]
        /*if(!params.max) params.max=2
        [goodsInstanceList:
                 new grails.orm.PagedResultList(Goods.list(params),Goods.count())
        ]*/
    }

    def show(Goods goodsInstance) {
        respond goodsInstance
    }

    def create() {
        respond new Goods(params)
    }

    @Transactional
    def save(Goods goodsInstance) {

        println goodsInstance
        if (goodsInstance == null) {
            notFound()
            return
        }
        println 'xxxxxxxxxxxx'
        if (goodsInstance.hasErrors()) {
            println '>>>>>>>>>>>>>>>>'+goodsInstance.errors
            respond goodsInstance.errors, view:'create'
            return
        }

        upLoadImage(goodsInstance)

      /*  String photoUrl=uploadImage()//调用上传图片的方法，返回一个储//存图片的路径。*/
      /*  goodsInstance.photoUrl=photoUrl//存储图片路径
        println goodsInstance.photoUrl
        println 'xxxxxxxxxxxxxx'*/

        goodsInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'defaul' +
                        't.created.message', args: [message(code: 'goods.label', default: 'Goods'), goodsInstance.id])
                redirect goodsInstance
            }
            '*' { respond goodsInstance, [status: CREATED] }
        }
    }

    private void upLoadImage(Goods goodsInstance) {
        def f = request.getFile('pictureUrl')//获取前台页面表单控件中的文件名称
        if ("${f.originalFilename}".trim() == "") {
            goodsInstance.photoUrl = params.get('photoCover')
            println params.get('photoCover')
            println goodsInstance.photoUrl
        } else if (!f.empty) {
            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/payload/")
            userDir.mkdirs()
            f.transferTo(new File(userDir, f.originalFilename))
            goodsInstance.photoUrl = f.originalFilename
        }
    }

    def edit(Goods goodsInstance) {
        respond goodsInstance
    }

    @Transactional
    def update(Goods goodsInstance) {
        if (goodsInstance == null) {
            notFound()
            return
        }

        upLoadImage(goodsInstance)

        if (goodsInstance.hasErrors()) {
            respond goodsInstance.errors, view:'edit'
            return
        }

        goodsInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'Goods.label', default: 'Goods'), goodsInstance.id])
                redirect goodsInstance
            }
            '*'{ respond goodsInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(Goods goodsInstance) {

        if (goodsInstance == null) {
            notFound()
            return
        }

        goodsInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'goods.label', default: 'Goods'), goodsInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'goods.label', default: 'Goods'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
    def searchForm(){   }

    def search(){
        if(!params.max ) params.max=3
        if(!params.offset) params.offset=0
        def parentCategory = Category.findByCategoryName(params.categoryName)
        def categoryList
        if(parentCategory)
        {
            categoryList =  Category.findByParentCategory(parentCategory)
            def goodList1 = Goods.findByCategoryInList(categoryList)
            goodList1.findAll {
                if (params.title){
                    like('title',"%${params.title}%")
                }
                if (params.description){
                    like('description',"%${params.description}%")
                }
                if (params.priceLow){
                    ge('price',new BigDecimal(params.priceLow))
                }
                if (params.priceHigh){
                    le('price',new BigDecimal(params.priceHigh))
                }
                if (params.author)
                {
                    like('author',"%${params.author}%")
                }
                if (params.publish)
                {
                    like('publish',"%${params.publish}%")
                }
            }
        }
        if(!categoryList)
        {
        }
        def serachClosure = {
            if (params.categoryName){
                    category {
                        eq('categoryName', params.categoryName)
                }
            }
            if (params.title){
                like('title',"%${params.title}%")
            }
            if (params.description){
                like('description',"%${params.description}%")
            }
            if (params.priceLow){
                ge('price',new BigDecimal(params.priceLow))
            }
            if (params.priceHigh){
                le('price',new BigDecimal(params.priceHigh))
            }
            if (params.author)
            {
                like('author',"%${params.author}%")
            }
            if (params.publish)
            {
                like('publish',"%${params.publish}%")
            }
        }
        def c = Goods.createCriteria()
        params.sort="price"
        params.order="asc"
        def goodList=c.list(params,serachClosure)
        def goodsCount=goodList.totalCount
       println  "$goodsCount"
        render(view:'index',model:[goodsInstanceList:goodList,goodsInstanceCount: goodsCount] )
    }

/*    def uploadImage(){//上传图片到本地文件夾中
        String  goodsInstance=new Goods(params)
        println 'yyyyyyyy'
      //  def fileName
        //def filePath
        def f = request.getFile('pictureUrl')//获取前台页面表单控//中的文件名称
        println f
        if (!f.empty) {
           // String  fileProName = f.originalFilename
            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/payload/")
            userDir.mkdirs()
            f.transferTo(new File(userDir, f.originalFilename))
            println f.originalFilename
            return f.originalFilename
        }
//        println f.originalFilename
        return   fileName    //返回文件名称
    }*/



}
